<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\ImRequest;
use Agent;
use App\Models\User;
use App\Models\Group;
use App\Models\Message;
use App\Models\LatestMessage;
use App\Http\Resources\UserResource;
use App\Http\Resources\GroupResource;
use App\Http\Resources\MessageResource;
use App\Http\Resources\LatestMessageResource;

class ImController extends Controller
{
    //绑定用户信息到”群里面“，每次更新群关系后需重新绑定
    public function bindUid(ImRequest $request)
    {
        $user = $request->user();

        // dd($user);
        // return ['code'=>0,'msg'=>'ok','data'=>['token'=>$user->currentAccessToken()->tokenable]];

        $currentAccessToken = $user->currentAccessToken();
        $gateway = app('gateway');
        $gateway->bindUid($request->client_id, $currentAccessToken->id);

        $groups = $user->groups()->get();
        $friendGroups = $user->friendGroups()->get();
        \Log::info('start Group', [
            
            ]);
        foreach ($groups as $group) {//大群
            \Log::info('group', [
                'user_id'=>$user->id,
                'group_id'=>$group->id,
            ]);
            $gateway->joinGroup($request->client_id, $group->id);
        }
        \Log::info('start friendGroup', [
            
        ]);
        foreach ($friendGroups as $friendGroup) {//和好友的群,只有两人
            \Log::info('friendGroup', [
                'user_id'=>$user->id,
                'group_id'=>$friendGroup->id,
            ]);
            $gateway->joinGroup($request->client_id, $friendGroup->id);
        }

        return response()->json(['code'=>0,'msg'=>'','data'=>[]]);
    }

    //不用登录就可在大群里聊
    public function bindGroupUid(ImRequest $request)
    {


        // dd($user);
        // return ['code'=>0,'msg'=>'ok','data'=>['token'=>$user->currentAccessToken()->tokenable]];


        $gateway = app('gateway');

        if ($request->customer_service) {//客服
            foreach (range(1, 10) as $id) {
                $gateway->joinGroup($request->client_id, $id);//绑定到10个群里，相当于和10个用户聊天
            }
        } else {//顾客
            $gateway->joinGroup($request->client_id, $request->to_id??1);//默认绑定到大群里
        }



        return response()->json(['code'=>0,'msg'=>'','data'=>[]]);
    }


    public function send(ImRequest $request)
    {
        $gateway = app('gateway');
        $user = $request->user();

        $currentAccessToken = $user->currentAccessToken();

        \Log::info('start:getClientIdByUid', []);
        $currentClientIds = $gateway->getClientIdByUid($currentAccessToken->id);//这是一个数组
        // if(isset($data['client_id']))

        $data = $request->validationData();
        if(isset($data['client_id'])&&in_array($data['client_id'],$currentClientIds)){
            $currentClientId = [$data['client_id']];
        }else{
            $currentClientId = null;
        }


        $data['from'] = (new UserResource($user));
        $data['from_id'] = $user->id;

        $data['sended_at'] = now()->format('Y-m-d H:i:s');



        switch ($data['type']) {
            case 'group':
                unset($data['client_id']);
                $toGroup = Group::findOrFail($data['to']['id']);
                $data['to'] = (new GroupResource($toGroup));
                $data['to_id'] = $toGroup->id;
                \Log::info('group_id:'.$data['to']['id']);
                app('gateway')->sendToGroup((int)$data['to']['id'], $data, $currentClientId, 'im_group_message');
                break;
            case 'friend':
                unset($data['client_id']);
                $toGroup = Group::findOrFail($data['to']['id']);
                $data['to_id'] = $toGroup->id;
                \Log::info('group_id:'.$data['to']['id']);
                app('gateway')->sendToGroup((int)$data['to']['id'], $data, $currentClientId, 'im_friend_message');
                break;
        }

        if (config('im.save_message')) {//是否支持保存数据到数据库，默认true
            event(new \App\Events\ImSend($data));
        }

        return response()->json(['code'=>0,'msg'=>'','data'=>['message'=>$data]]);
    }

    //不用登录就能发送信息，不会保存消息记录
    public function groupSend(ImRequest $request)
    {
        $data = $request->validationData();


        $data['sended_at'] = now()->format('Y-m-d H:i:s');

        $currentClientId = $data['client_id'];

        switch ($data['type']) {
            case 'group':
                unset($data['client_id']);
                
                \Log::info('group_id:'.$data['to']['id']);
                app('gateway')->sendToGroup((int)$data['to']['id'], $data, $currentClientId, 'im_group_message');
                // $gateway->sendToUid($currentAccessToken->id,$data);
                break;
            case 'friend':
                unset($data['client_id']);
                app('gateway')->sendToGroup((int)$data['to']['id'], $data, $currentClientId, 'im_friend_message');
                break;


        }

        // if(config('im.save_message')){//是否支持保存数据到数据库，默认true
        //     event(new \App\Events\ImSend($data));
        // }
        return response()->json(['code'=>0,'msg'=>'','data'=>['message'=>$data]]);
    }

    //加群（在一个群里面，快速拉自己的好友入群）
    public function joinGroup(ImRequest $request)
    {
        $group= Group::findOrFail($request->group_id);

        $joinUserIds = $request->join_user_ids;
        //todo 限制拉自己的好友

        $state = 0; //状态为1 前端需要重新跳到新建的群

        if ($group->type==1) {//这是个群聊群，直接加入

            $group->users()->syncWithoutDetaching($joinUserIds);
        } elseif ($group->type==0) {//这是"好友"的群，需重新新建个群，把好友和新的一起加入进去

            $newGroup = Group::factory()->create();
            $newGroup->type = 1;
            $newGroup->save();

            $userIds = $group->users()->get(['id'])->pluck('id')->toArray();

            $userIds = array_merge($userIds, $joinUserIds);
            $newGroup->users()->sync($userIds);
            $state = 1;

            $group = $newGroup;
        }

        //todo 给加群的用户发送一条系统通知，让对方重新绑定下wbsocket，可以接收信息

        //可放在事件中
        $gateway = app('gateway');
        $currentAccessToken = $request->user()->currentAccessToken();
        $users = $group->users()->with(['tokens'=>function ($query) {
            $query->where('last_used_at', '>', now()->subMinutes(60*24));//一天之内的才推送
        }])->get();
        foreach ($users as $user) {
            foreach ($user->tokens as $token) {
                // if($currentAccessToken->id!=$token->id){//都需要重新绑定
                $gateway->sendToUid($token->id, ['type'=>'refresh_user'], 'im_refresh_user');
                // }
            }
        }


        
        return response()->json(['code'=>0,'msg'=>'','data'=>['state'=>$state ,'group'=>new GroupResource($group)]]);
    }

    //获取聊天记录
    public function messages(ImRequest $request)
    {
        $group_id = $request->input('group_id');

        $group = Group::findOrFail($group_id);
        $user = $request->user();

        if (!$group->users()->where('id', $user->id)->first()) {
            return response()->json(['code'=>1,'msg'=>'没有权限！！','data'=>[]]);
        }


        $limitMessage = Message::where('to_id', $group_id)->where('unique_slug', $request->input('unique_slug'))->first();
        if ($limitMessage) {
            $messages = Message::where('to_id', $group_id)->where('id', '<', $limitMessage->id)->latest('created_at')->paginate($request->limit??30);
        } else {
            $messages = Message::where('to_id', $group_id)->latest('created_at')->paginate($request->limit??30);
        }
        $messages = $messages->sortBy('id');

        $messages = MessageResource::collection($messages);
        $count = Message::where('to_id', $group_id)->count();
        return response()->json(['code'=>0,'msg'=>'','data'=>['messages'=>$messages,'t_messages'=>[],'count'=>$count]]);
    }



    //获取最新消息（暂时没启用）
    public function getLatestMessages(ImRequest $request)
    {
        $user = $request->user();
        $groupIds = $user->getGroupIds();
        $latestMessages = LatestMessage::whereIn('group_id', $groupIds)->get();
        $latestMessages = LatestMessageResource::collection($latestMessages);
        return response()->json(['code'=>0,'msg'=>'','data'=>['lists'=>$latestMessages]]);
    }

    //获取群里面的用户
    public function getGroupUsers(ImRequest $request)
    {
        $group_id = $request->input('id');

        $group = Group::findOrFail($group_id);
        $user = $request->user();

        if (!$group->users()->where('id', $user->id)->first()) {
            return response()->json(['code'=>1,'msg'=>'没有权限！！','data'=>[]]);
        }

        $users = $group->users()->get();

        return response()->json(['code'=>0,'msg'=>'','data'=>[
            'list' => UserResource::collection($users)
        ]]);
    }

    //两个用户是否可以私聊小群（两个人的小群是"好友聊天"），并返回“群”ID
    public function userToUserGroup(ImRequest $request)
    {
        $userId = $request->user_id;

        $userT = User::findOrFail($userId);

        $user = $request->user();

        if ($user->id>$userId) {
            $userToUser = $userId.'-'.$user->id;
        } else {
            $userToUser = $user->id.'-'.$userId;
        }

        $group = Group::where('user_to_user', $userToUser)->where('type', 0)->first();

        if ($group) {//之前聊过天
            return response()->json(['code'=>0,'msg'=>'','data'=>[
                'group' => new GroupResource($group)
            ]]);
        }

        //判断两个用户是否可以私聊（有交集）
        $userGroups = $user->groups()->get();
        $userTGroups = $userT->groups()->get();
        $inGroupIds = array_intersect($userGroups->pluck('id')->toArray(), $userTGroups->pluck('id')->toArray());
        if (empty($inGroupIds)) {//没有交集
            return response()->json(['code'=>1,'msg'=>'不能聊天！！','data'=>[]]);
        }

        //给两个用户创建一个私聊群（好友聊天）
        $userToUserGroup = new Group();
        $userToUserGroup->type = 0;
        $userToUserGroup->user_to_user = $userToUser;
        $userToUserGroup->name = $user->name.'-'.$userT->name;
        $userToUserGroup->save();

        $userToUserGroup->users()->sync([$user->id,$userT->id]);


        return response()->json(['code'=>0,'msg'=>'','data'=>[
                'group' => new GroupResource($userToUserGroup)
            ]]);
    }
}
